import erdfServer from 'erdf-server'

var util = {}
let config = {
  beforeRequest: function(value) {
    if (value.data[0] == 'charts') return false
  },
  afterResponse: function() {
    return false
  }
}
var autoCode = {}

/**
 * 返回两个对象不同的部分
 * @param {Object} obj1 - 旧的对象
 * @param {Object} obj2 - 新的对象
 */
util.difference = function(obj1, obj2) {
  var result = {}
  for (var key in obj1) {
    if (Object.prototype.hasOwnProperty.call(obj1, key)) {
      if (Object.prototype.hasOwnProperty.call(obj2, key)) {
        if (typeof obj1[key] == 'object') {
          if (JSON.stringify(obj1[key]) != JSON.stringify(obj2[key])) {
            result[key] = obj2[key]
          }
        } else if (!obj1[key]) {
          result[key] = obj2[key]
        } else {
          if (obj1[key] !== obj2[key]) {
            result[key] = obj2[key]
          }
        }
      } else {
        result[key] = obj1[key]
      }
    }
  }
  return result
}
/**
 * 获取随机id
 */
util.getGuid = function() {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  }
  return S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4()
}

/**
 * 将目标对象中源对象拥有的属性进行拷贝
 * @param {Object} source - 拷贝源
 * @param {Object} target - 拷贝目标
 */
util.copyOwnProperty = function(source, target) {
  if (!source || !target) return
  for (let prop in target) {
    if (typeof target[prop] != 'undefined') {
      target[prop] = source[prop]
    }
  }
}
/**
 * 将树结构转换成数组
 * @param {Object} treeData - 树结构数据
 * @param {Object} field - 子级字段名称
 */
util.treeToArray = function(treeData, field) {
  var result = []
  if (!field) field = 'children'
  for (var key in treeData) {
    var obj = treeData[key]
    var clone = JSON.parse(JSON.stringify(obj))
    delete clone[field]
    result.push(clone)
    if (obj[field]) {
      obj[field].forEach(element => {
        element.parentId = obj.id
      })
      var tmp = util.treeToArray(obj[field], field)
      result = result.concat(tmp)
    }
  }
  return result
}

/**
 * 把数组转化成树结构对象
 */
util.convertTree = function() {
  let self = this
  this.treeObj = function(originObj) {
    //对象深拷贝
    let obj = {}
    for (let key in originObj) {
      let val = originObj[key]
      if (val != null) {
        if (Array.isArray(val)) {
          obj[key] = JSON.parse(JSON.stringify(val))
        } else {
          obj[key] = typeof val === 'object' ? JSON.parse(JSON.stringify(val)) : val
        }
      }
    }
    //对象新增children键值，用于存放子树
    obj['children'] = obj['children'] ? JSON.parse(JSON.stringify(obj['children'])) : []
    return obj
  }
  this.setTree = function(data) {
    let resData = data
    let tree = []
    //找寻根节点
    for (let i = 0; i < resData.length; i++) {
      if (resData[i].parentId === '' || resData[i].parentId === null || resData[i].parentId === '-1' || resData[i].parentId === '0') {
        tree.push(self.treeObj(resData[i]))
        resData.splice(i, 1)
        i--
      }
    }
    run(tree)
    //找寻子树
    function run(chiArr) {
      if (resData.length !== 0) {
        for (let i = 0; i < chiArr.length; i++) {
          for (let j = 0; j < resData.length; j++) {
            if (chiArr[i].id === resData[j].parentId) {
              let obj = self.treeObj(resData[j])
              chiArr[i].children.push(obj)
              resData.splice(j, 1)
              j--
            }
          }
          if (chiArr[i].children) {
            if (chiArr[i].children.length == 0) {
              delete chiArr[i].children
            } else {
              run(chiArr[i].children)
            }
          }
        }
      }
    }
    return tree
  }
}
/**
 * @description 将日期变为短日期，一般用于列表里展示时间
 */
util.formatTimeToMin = function(time) {
  if (!time) {
    return ''
  }
  let tempTime = new Date(time)
  let year = tempTime.getFullYear()
  let month = tempTime.getMonth() + 1 < 10 ? '0' + (tempTime.getMonth() + 1) : tempTime.getMonth() + 1
  let day = tempTime.getDate() < 10 ? '0' + tempTime.getDate() : tempTime.getDate()
  let hour = tempTime.getHours() < 10 ? '0' + tempTime.getHours() : tempTime.getHours()
  let minute = tempTime.getMinutes() < 10 ? '0' + tempTime.getMinutes() : tempTime.getMinutes()
  return `${year}-${month}-${day} ${hour}:${minute}`
}

/**
 * 原数组去除数组
 * @param {Array} originalArr - 原数组
 * @param {Array} removeArr - 需要去除的数组
 * @param {string} key - 关键字
 * @returns {Array}
 */
util.originalArrRemoveArr = (originalArr, removeArr, key) => {
  const newArr = JSON.parse(JSON.stringify(originalArr))
  removeArr = JSON.parse(JSON.stringify(removeArr))
  if (removeArr.length && newArr.length) {
    for (let i = 0; i < removeArr.length; i++) {
      for (let j = 0; j < newArr.length; j++) {
        if (removeArr[i][key] === newArr[j][key]) {
          newArr.splice(j, 1)
        }
      }
    }
  }
  return newArr
}
/**
 * 生成序号
 * @param {Array} originalArr - 原数组
 * @param {Number} index - 序号初始值
 * @returns {Array}
 */
util.generateIndex = (originalArr, index) => {
  const newArr = JSON.parse(JSON.stringify(originalArr))
  newArr.forEach(item => {
    item.index = index
    index++
  })
  return newArr
}

// 大数组去除小数组
util.handleRemoveArr = function(removeArr, originalArr, props) {
  if (removeArr.length && originalArr.length) {
    for (let i = 0; i < removeArr.length; i++) {
      for (let j = 0; j < originalArr.length; j++) {
        if (removeArr[i][props] === originalArr[j][props]) {
          originalArr.splice(j, 1)
        }
      }
    }
  }
}

/**
 * 返回两个对象不同的部分
 * @param {Object} arr1 - 数组1
 * @param {Object} arr2 - 数组2
 * @param {Object} props - 键名
 */
util.duplicate = function(arr1, arr2, props) {
  if (arr1.length && arr2.length) {
    for (let i = 0; i < arr1.length; i++) {
      for (let j = 0; j < arr2.length; j++) {
        if (arr1[i][props] === arr2[j][props]) {
          arr2.splice(j, 1)
        }
      }
    }
  }
}

/**  
 *desc: base64转文件并下载
 * @param base64 {String} : base64数据
 * @param fileType {String} : 要导出的文件类型png,pdf,doc,mp3等
 @param fileName {String} : 文件名
 */
util.downloadFile = function(base64, fileName, fileType) {
  const typeHeader = 'data:application/' + fileType + ';base64,' // 定义base64 头部文件类型
  const converedBase64 = typeHeader + base64 // 拼接最终的base64
  const blob = this.base64ToBlob(converedBase64, fileType) // 转成blob对象
  this.downloadExportFile(blob, fileName, fileType) // 下载文件
}

/** desc: base64对象转blob文件对象
  // * @param urlData  ：数据的base64对象
  // * @param type  ：类型
   @returns {Blob}：Blob文件对象
  */
util.base64ToBlob = function(urlData, type) {
  const arr = urlData.split(',')
  const array = arr[0].match(/:(.*?);/)
  const mime = (array && array.length > 1 ? array[1] : type) || type
  // 去掉url的头，并转化为byte
  const bytes = window.atob(arr[1])
  // 处理异常,将ascii码小于0的转换为大于0
  const ab = new ArrayBuffer(bytes.length)
  // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
  const ia = new Uint8Array(ab)
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  return new Blob([ab], {
    type: mime
  })
}

// * desc: 下载导出文件
// * @param blob  ：返回数据的blob对象或链接
// * @param fileName  ：下载后文件名标记
// * @param fileType  ：文件类 word(docx) excel(xlsx) ppt等
util.downloadExportFile = function(blob, fileName, fileType) {
  const downloadElement = document.createElement('a')
  let href = blob
  if (typeof blob === 'string') {
    downloadElement.target = '_blank'
  } else {
    href = window.URL.createObjectURL(blob) // 创建下载的链接
  }
  downloadElement.href = href
  downloadElement.download = fileName + '.' + fileType // 下载后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() // 触发点击下载
  document.body.removeChild(downloadElement) // 下载完成移除元素
  if (typeof blob !== 'string') {
    window.URL.revokeObjectURL(href) // 释放掉blob对象
  }
}

/**
 * @description 计算两个日期差值（天）
 * @param sDate1: 前一个日期，格式为2006-12-18
 * @param sDate2: 前一个日期，格式为2006-12-18
 */
util.dateDiff = function(sDate1, sDate2) {
  let dateSpan, iDays
  sDate1 = Date.parse(sDate1)
  sDate2 = Date.parse(sDate2)
  dateSpan = sDate2 - sDate1
  dateSpan = Math.abs(dateSpan)
  iDays = Math.floor(dateSpan / (24 * 3600 * 1000)) + 1
  return iDays
}

/**
 * @description 计算两个时间差值（天）
 * @param sDate1: 前一个日期，格式为2006-12-18
 * @param sDate2: 前一个日期，格式为2006-12-18
 */
util.timeDiff = function(beginTime, endTime) {
  if(!beginTime || !endTime){
    return '-'
  }
  var dateBegin = new Date(beginTime)
  var dateEnd = new Date(endTime)
  var dateDiff = dateEnd.getTime() - dateBegin.getTime() //时间差的毫秒数
  var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)) //计算出相差天数
  var leave1 = dateDiff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
  var hours = Math.floor(leave1 / (3600 * 1000)) //计算出小时数
  //计算相差分钟数
  // var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
  // var minutes = Math.floor(leave2 / (60 * 1000)) //计算相差分钟数
  //计算相差秒数(一般不需要计算到秒)
  // var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
  // var seconds = Math.round(leave3 / 1000)
  // console.log('相差' + dayDiff + '天' + hours + '小时' + minutes + '分钟' + seconds + '秒')
  return dayDiff + '天' + hours + '小时'
}

/**
 * @description 申请自动编号
 * @param code: 对应编号规则中的功能号
 * @param number: 生成编号的数量，默认值为1
 */

autoCode.getSerialNumber = async (code, number = 1) => {
  if (sessionStorage.getItem('authorization_token')) {
    config.token = sessionStorage.getItem('authorization_token')
  }
  let serialNumber = null
  await erdfServer(config)
    .erdfRequest('/server/business-manufacture/base/RuleNumberSerial/getSerialNumber', [code, number], 'post')
    .then(res => {
      serialNumber = res
    })
    .catch(e => {
      self.$message.error(e.data.message)
    })
  return serialNumber
}

/**
 * @description 确认自动编号的使用
 * @param serials {Array}: 申请时返回的编号数组，会将数组内第所有编号对象都确认
 */

autoCode.confirmCode = async serials => {
  if (sessionStorage.getItem('authorization_token')) {
    config.token = sessionStorage.getItem('authorization_token')
  }
  await erdfServer(config)
    .erdfRequest('/server/business-manufacture/base/RuleNumberSerial/confirm', [serials], 'post')
    .then(() => {})
    .catch(e => {
      self.$message.error(e.data.message)
    })
}

/**
 * @description 过期销毁自动编号
 */
autoCode.destroyCode = async () => {
  if (sessionStorage.getItem('authorization_token')) {
    config.token = sessionStorage.getItem('authorization_token')
  }
  await erdfServer(config)
    .erdfRequest('/server/business-manufacture/base/RuleNumberSerial/expireDestroy', [], 'post')
    .then(() => {})
    .catch(e => {
      self.$message.error(e.data.message)
    })
}

/**
 * @description 实时销毁自动编号
 * @param serials {Array}: 申请时返回的编号数组，会将数组内第所有编号对象都确认
 */

autoCode.realDestroy = async serials => {
  if (sessionStorage.getItem('authorization_token')) {
    config.token = sessionStorage.getItem('authorization_token')
  }
  await erdfServer(config)
    .erdfRequest('/server/business-manufacture/base/RuleNumberSerial/realDestroy', [serials], 'post')
    .then(() => {})
    .catch(e => {
      self.$message.error(e.data.message)
    })
}

/** 获取路由上的参数 */
export const getQueryString = name => {
  let index = window.location.search.indexOf('?')
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  let r = window.location.search.slice(index + 1).match(reg)
  if (r != null) {
    return decodeURIComponent(r[2])
  }
  return null
}

export { autoCode }
export default util
